using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
    public class StudentStageRepository : Repository<StudentStage>, IStudentStageRepository
    {
        private readonly IStudentScoreRepository _studentScoreRepository;
        protected override Expression<Func<StudentStage, int>> PrimaryKeyExpression => r => r.Id;

        public StudentStageRepository(ApiDBContent context,
        IStudentScoreRepository studentScoreRepository) : base(context)
        {
            _studentScoreRepository = studentScoreRepository;
        }

        protected override void UpdateEntitiesAfterDelete(IEnumerable<StudentStage> entities, ApiDBContent context)
        {
            var ids = entities.Select(r => r.Id).ToList();
            var studentScores = _studentScoreRepository.FindAll().Where(r => ids.Contains(r.StageId));
            _studentScoreRepository.DeleteRange(studentScores);
        }

        protected override void UpdateEntitiesBeforeCreate(IEnumerable<StudentStage> entities, ApiDBContent context)
        {
            foreach (var entity in entities)
            {
                entity.UserId = AuthInfo.UserId;
            }
        }

        protected override IQueryable<StudentStage> FilterByAuthInfo(IQueryable<StudentStage> queryable, ApiDBContent context)
        {
            if (AuthInfo.IsAdmin)
            {
                return queryable;
            }

            queryable = queryable.Where(r => r.UserId == AuthInfo.UserId);
            return queryable;
        }
    }
}